package net.arogarth.aws.android.lib;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import net.arogarth.aws.android.lib.models.S3Bucket;

public class AmazonS3 extends AmazonAWS {
	public AmazonS3() {
		super();

//		this.setRegion("");
//		this.service = "eu-west-1.elasticloadbalancing";
		this.service = AwsSettings.getAwsRegion() + ".s3";
		this.version = "2006-03-01";
	}

	public List<S3Bucket> listBuckets() {
		List<S3Bucket> buckets = new ArrayList<S3Bucket>();
		
		try {
			Element root = this.execute();
			
			XPath xpath = XPathFactory.newInstance().newXPath();
			NodeList items = (NodeList) xpath.evaluate("//Bucket/*", root,
					XPathConstants.NODESET);
			
			for (int i = 0; i < items.getLength(); i++) {
				S3Bucket bucket = new S3Bucket();
				Node item = items.item(i);
				NodeList properties = item.getChildNodes();

				for (int j = 0; j < properties.getLength(); j++) {
					Node property = properties.item(j);
					String name = property.getNodeName();
					if (property.getFirstChild() == null)
						continue;
					String value = property.getFirstChild().getNodeValue();

					if (name.equalsIgnoreCase("Name")) {
						bucket.setBucketName(value);
					} else if (name.equalsIgnoreCase("CreationDate")) {
						bucket.setCreationDate(value);
					}
					
				}
				buckets.add(bucket);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buckets;
	}
}
